import {
	Button,
	Form,
	Row,
	Col,
	Input,
	Select,
	Cascader,
	Collapse,
	Modal,
	message,
	Upload,
} from 'antd'
import React, {useState, useEffect} from 'react'
import type {ColumnsType} from 'antd/es/table'
import {history, useModel} from 'umi'
import moment from 'moment'
import type {UploadFile} from 'antd/es/upload/interface'
import CustomTable from '@/components/Table'
import SearchForm from '@/components/SearchForm'
import styles from './index.less'
import {
	getFindHistoryListByDate,
	graderecordInfo,
} from '@/service/supplier/graderecord'
import {getDict} from '@/service/common/dict'
import {getSupplierType} from '@/utils/common'
import {getPublicDownloadUrl, uploadFileUrl} from '@/service/common/upload'

const {Panel} = Collapse
const {Dragger} = Upload
interface DataType {
	scoreFile: any
	id: string
	createTime: string
	score: string
	scoreGrade: string
	createUserName: string
}

const formItemLayout = {
	labelCol: {flex: '70px'},
	wrapperCol: {flex: '1'},
}

const customizeHeader = (value: string) => (
	<div>
		<div className={styles.tip} />
		{value}
	</div>
)

const details = (props: any) => {
	const {query} = props.location
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [form] = Form.useForm()
	const [modelForm] = Form.useForm()
	const [supplierDetail, setSupplierDetail] = useState<any>()
	const [gradeDetail, setGradeDetail] = useState<any>()
	const [historyGradeDetail, setHistoryGradeDetail] = useState<any>()
	const [fileList, setFileList] = useState<UploadFile[]>([])
	const [modalFileList, setModalFileList] = useState<UploadFile[]>([])
	const [supplierTypeData, setSupplierTypeData] =
		useState<supplierAPI.supplierType>([])
	// 字典数据
	const [dictData, setDictData] = useState<any>({})
	const [dataSource, setDataSource] = useState([])
	const [searchData, setSearchData] = useState({})
	const [loading, setLoading] = useState<boolean>(false)
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	useEffect(() => {
		getDict(
			{
				dictKeys: [
					'ZC_GYS',
					'JC_GYS',
					'CZ_GYS',
					'SP_GYS',
					'DYY_GYS',
					'CS_GYS',
					'Supplier_Rating',
				],
			},
			(res: any) => {
				setDictData(res)
				// 组装供应商类型
				const newData = getSupplierType([
					res.ZC_GYS,
					res.JC_GYS,
					res.CZ_GYS,
					res.SP_GYS,
					res.DYY_GYS,
					res.CS_GYS,
				])
				setSupplierTypeData(newData)
			},
		)
	}, [])

	// 获取历史评级列表
	const getData = () => {
		setLoading(true)
		getFindHistoryListByDate({
			...params,
			...searchData,
			supplierId: query.id,
		})
			.then((res: any) => {
				setDataSource(res?.data?.records)
				setTotal(res?.data?.total)
				setLoading(false)
			})
			.catch((err: any) => {
				setDataSource([])
				message.error(err)
				setLoading(false)
			})
	}
	useEffect(() => {
		getData()
	}, [params])
	const getDetails = () => {
		graderecordInfo(query?.id).then((res: any) => {
			if (res?.data) {
				setGradeDetail(res.data?.gradeList?.[0])
				setSupplierDetail(res.data)
				form.setFieldsValue({
					supplierCode: res.data?.supplierCode,
					supplierName: res.data?.supplierName,
					supplierType: res.data?.supplierType?.split(','),
					scoreGrade: res.data?.gradeList?.[0]?.scoreGrade || '-',
				})
				const url = res?.data?.gradeList?.[0]?.scoreFile
					?.split(',')
					?.map(Number)
				if (url?.length) {
					getPublicDownloadUrl(url)
						.then((result: any) => {
							const urlData = result?.data?.map(
								(item: {
									id: any
									filename: string
									url: string
								}) => ({
									uid: item?.id,
									name: item?.filename,
									url: item?.url,
								}),
							)
							setFileList(urlData)
						})
						.catch((err: any) => {
							message.error(err)
						})
				}
			}
		})
	}
	useEffect(() => {
		getDetails()
	}, [query])

	const columns: ColumnsType<DataType> = [
		{
			title: '评级时间',
			dataIndex: 'createTime',
			align: 'center',
			render: (text) => moment(text).format('YYYY-MM-DD'),
			width: 150,
		},
		{
			title: '供应商综合评分',
			dataIndex: 'score',
			align: 'center',
			width: 150,
		},
		{
			title: '供应商评级',
			dataIndex: 'scoreGrade',
			align: 'center',
			width: 120,
			render: (text) => (
				<Select
					value={text}
					disabled
					fieldNames={{value: 'dictKey', label: 'dictValue'}}
					options={dictData?.Supplier_Rating}
				/>
			),
		},
		{
			title: '操作人',
			dataIndex: 'createUserName',
			align: 'center',
			width: 120,
		},
		{
			title: '操作',
			key: 'action',
			align: 'center',
			width: 100,
			render: (text: any, record) => (
				<Button
					type="link"
					onClick={() => {
						setHistoryGradeDetail(record)
						const {scoreGrade} = record
						modelForm.setFieldsValue({
							supplierCode: supplierDetail?.supplierCode,
							supplierName: supplierDetail?.supplierName,
							supplierType:
								supplierDetail?.supplierType?.split(','),
							scoreGrade,
						})
						const url = record?.scoreFile?.split(',')?.map(Number)
						if (url?.length) {
							getPublicDownloadUrl(url)
								.then((result: any) => {
									const urlData = result?.data?.map(
										(item: {
											id: any
											filename: string
											url: string
										}) => ({
											uid: item?.id,
											name: item?.filename,
											url: item?.url,
										}),
									)
									setModalFileList(urlData)
									setIsModalOpen(true)
								})
								.catch((err: any) => {
									message.error(err)
								})
						}
					}}>
					详情
				</Button>
			),
		},
	]

	const formItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'time',
					subtype: 'date',
					label: '评级时间',
					name: 'date',
					key: 'date',
				},
				{},
				{},
			],
		},
	]

	const onFinish = (value: any) => {
		if (value?.date) {
			setSearchData({
				date: moment(value?.date).format('YYYY-MM-DD'),
			})
		} else {
			setSearchData({})
		}
		setParams({
			current: 1,
			size: 10,
		})
	}
	const onReset = () => {
		setSearchData({})
		setParams({
			current: 1,
			size: 10,
		})
	}

	const uploadProps = {
		action: uploadFileUrl,
		name: fileName, // 滴滴上传:file,测试上传:files
		data: {
			modelName: 'spGrade',
			targetAttr: 1,
		},
		fileList,
	}
	const modalUploadProps = {
		action: uploadFileUrl,
		name: fileName, // 滴滴上传:file,测试上传:files
		data: {
			modelName: 'spGrade',
			targetAttr: 1,
		},
		fileList: modalFileList,
	}
	return (
		<div className={styles.details}>
			<Collapse
				collapsible="header"
				defaultActiveKey={['1']}
				ghost
				expandIconPosition="end">
				<Panel header={customizeHeader('当前评级信息')} key="1">
					<Form
						form={form}
						name="basic"
						layout="horizontal"
						labelCol={{flex: '140px'}}
						labelAlign="right"
						labelWrap
						autoComplete="off"
						disabled>
						<Row gutter={12}>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="供应商编号"
									name="supplierCode"
									rules={[
										{
											required: true,
										},
									]}>
									<Input placeholder="请输入" />
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="供应商类型"
									name="supplierType"
									rules={[{required: true}]}
									colon>
									<Cascader
										options={supplierTypeData}
										placeholder="请选择"
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="供应商名称"
									name="supplierName"
									rules={[
										{
											required: true,
											max: 20,
										},
									]}>
									<Input placeholder="请输入" />
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="供应商评级"
									name="scoreGrade"
									rules={[{required: true}]}
									className={styles.required}>
									<Select
										placeholder="请选择"
										allowClear
										fieldNames={{
											value: 'dictKey',
											label: 'dictValue',
										}}
										options={dictData?.Supplier_Rating}
									/>
								</Form.Item>
							</Col>
							<Col span={24}>
								<Form.Item label="服务类型" name="examineOrgId">
									<table
										border="1"
										className={styles.uploadWrap}>
										<tr>
											<td>供应商类型</td>
											<td>评分文件</td>
											<td>得分情况</td>
										</tr>
										<tr>
											<td>
												<Cascader
													value={supplierDetail?.supplierType.split(
														',',
													)}
													options={supplierTypeData}
													disabled
												/>
											</td>
											<td>
												<Dragger {...uploadProps} />
											</td>
											<td>
												{gradeDetail?.score || '得分'}
											</td>
										</tr>
									</table>
								</Form.Item>
							</Col>
						</Row>
					</Form>
				</Panel>
				<Panel header={customizeHeader('历史评级记录')} key="2">
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formItems}
						formLayout={formItemLayout}
						style={{marginBottom: '12px'}}
					/>
					<CustomTable
						params={params}
						columns={columns}
						total={total}
						pagination
						callback={(pagination: any) => {
							setParams(pagination)
						}}
						loading={loading}
						dataSource={dataSource}
					/>
				</Panel>
			</Collapse>
			<div className={styles.wrap}>
				<Button
					onClick={() => {
						history.go(-1)
					}}>
					返回
				</Button>
			</div>
			<Modal
				title="评级详情"
				open={isModalOpen}
				onOk={() => setIsModalOpen(true)}
				onCancel={() => setIsModalOpen(false)}
				width={750}
				destroyOnClose
				footer={null}
				className={styles.modal}>
				<Form
					form={modelForm}
					name="basic"
					layout="horizontal"
					labelCol={{flex: '140px'}}
					labelAlign="right"
					labelWrap
					autoComplete="off"
					disabled>
					<Row gutter={12}>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 12}}>
							<Form.Item
								label="供应商编号"
								name="supplierCode"
								rules={[
									{
										required: true,
									},
								]}>
								<Input placeholder="请输入" />
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 12}}>
							<Form.Item
								label="供应商类型"
								name="supplierType"
								rules={[{required: true}]}
								colon>
								<Cascader
									options={supplierTypeData}
									placeholder="请选择"
								/>
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 12}}>
							<Form.Item
								label="供应商名称"
								name="supplierName"
								rules={[
									{
										required: true,
										max: 20,
									},
								]}>
								<Input placeholder="请输入" disabled />
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}} lg={{span: 12}}>
							<Form.Item
								label="供应商评级"
								name="scoreGrade"
								rules={[{required: true}]}
								className={styles.required}>
								<Select
									placeholder="请选择"
									allowClear
									fieldNames={{
										value: 'dictKey',
										label: 'dictValue',
									}}
									options={dictData?.Supplier_Rating}
								/>
							</Form.Item>
						</Col>
						<Col span={24}>
							<Form.Item label="服务类型" name="examineOrgId">
								<table border="1" className={styles.uploadWrap}>
									<tr>
										<td>供应商类型</td>
										<td>评分文件</td>
										<td>得分情况</td>
									</tr>
									<tr>
										<td>
											<Cascader
												value={supplierDetail?.supplierType?.split(
													',',
												)}
												options={supplierTypeData}
												disabled
											/>
										</td>
										<td>
											<Dragger {...modalUploadProps} />
										</td>
										<td>
											{historyGradeDetail?.score ||
												'得分'}
										</td>
									</tr>
								</table>
							</Form.Item>
						</Col>
					</Row>
				</Form>
			</Modal>
		</div>
	)
}

export default details
